#include "ChessBoard.h"

ChessBoard::ChessBoard()
{
    for(int i = 0; i < 8; ++i) {
        for(int k = 0; k < 8; ++k) {
            fields[i][k] = new Field(Position::index2position(i, k));
        }
    }
}

void ChessBoard::init()
{
    fields[0][0]->put(new Rook(BLACK));
    fields[0][1]->put(new Knight(BLACK));
    fields[0][2]->put(new Bishop(BLACK));
    fields[0][3]->put(new Queen(BLACK));
    fields[0][4]->put(new King(BLACK));
    fields[0][5]->put(new Bishop(BLACK));
    fields[0][6]->put(new Knight(BLACK));
    fields[0][7]->put(new Rook(BLACK));

    fields[1][0]->put(new Pawn(BLACK));
    fields[1][1]->put(new Pawn(BLACK));
    fields[1][2]->put(new Pawn(BLACK));
    fields[1][3]->put(new Pawn(BLACK));
    fields[1][4]->put(new Pawn(BLACK));
    fields[1][5]->put(new Pawn(BLACK));
    fields[1][6]->put(new Pawn(BLACK));
    fields[1][7]->put(new Pawn(BLACK));

    fields[6][0]->put(new Pawn(WHITE));
    fields[6][1]->put(new Pawn(WHITE));
    fields[6][2]->put(new Pawn(WHITE));
    fields[6][3]->put(new Pawn(WHITE));
    fields[6][4]->put(new Pawn(WHITE));
    fields[6][5]->put(new Pawn(WHITE));
    fields[6][6]->put(new Pawn(WHITE));
    fields[6][7]->put(new Pawn(WHITE));

    fields[7][0]->put(new Rook(WHITE));
    fields[7][1]->put(new Knight(WHITE));
    fields[7][2]->put(new Bishop(WHITE));
    fields[7][3]->put(new Queen(WHITE));
    fields[7][4]->put(new King(WHITE));
    fields[7][5]->put(new Bishop(WHITE));
    fields[7][6]->put(new Knight(WHITE));
    fields[7][7]->put(new Rook(WHITE));

}

void ChessBoard::move(const QString &from, const QString &on)
{
        if(field(from)->getFigure() != nullptr) {
                if(field(on)->getFigure() != nullptr) {
                    field(on)->clear();
                }

                field(on)->put(field(from)->getFigure());
                field(from)->clear();

            emit repaint();
        }
}

PossibleMoves ChessBoard::getPossibleMovesFrom(const int y, const int x) const
{
    PossibleMoves possibleMoves;

    Figure * figure = fields[y][x]->getFigure();

    if(figure != nullptr) {
        AllMoves allMoves = figure->moves();

        //algorytm do edycji
        foreach(QVector<int> index, allMoves) {
            if(fields[index[0]][index[1]]->getFigure() != nullptr) {
                possibleMoves.onNonFreeFields.append(index);
            } else {
                possibleMoves.onFreeFields.append(index);
            }
        }
    }

    return possibleMoves;
}

Field * ChessBoard::field(int y, int x) const
{
    return fields[y][x];
}

Field * ChessBoard::field(const QString & position) const
{
    int index[2];
    Position::position2index(position, index);

    return fields[index[0]][index[1]];
}

ChessBoard::~ChessBoard()
{
    for(int i = 0; i < 8; ++i) {
        for(int k = 0; k < 8; ++k) {
            delete fields[i][k];
        }
    }
}
